﻿/**********************************************
 * 功能名称：作业动因量录入
编写人：  杨莹
建立时间： 杨 2008年11月14日
说明：
加载页面时，根据当前用户ID查询出责任部门，列表显示其作业中心列表。
作业中心列表中选择后，列表出作业中心对应的分配对象：目标作业中心；
在每行记录后面录入对应的动因量，点击按钮保存录入的信息。
 **************************************************************/

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using Hisun.Controllers;
using System.Text;
using System.Collections.Generic;

namespace Hisun.View.CostDriver
{
    public partial class CostDriverInput : AbcPageBase
    {
        HisunDBDataContext db = new HisunDBDataContext();
        public string alert;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
                DropDownList_CostCenter.Items.Clear();
                FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID));

                HiddenField_CurrentCenterId.Value = "";

            }
        }



        //查询当前操作员对应的作业中心列表
        private void FillData2DropDownList(int CenterID)
        {
            ChildCenterList myCenter = new ChildCenterList(CenterID);

            var myCenterFilters = myCenter.CostCenterlist.Where(p => new string[] { "A", "F", "M" }.Contains(p.类型) && p.停用 == false);


            foreach (var MylistItem in myCenterFilters)
            {

                if(MylistItem.作业中心名称.Contains(TextBox_FilterText.Text))
                {
                ListItem InsertItem = new ListItem(MylistItem.作业中心名称, MylistItem.作业中心ID.ToString());
                DropDownList_CostCenter.Items.Add(InsertItem);
                }
            }


        }

        //双击按钮的时候，填充当前的作业中心列表。
        protected void Button_fullCenterList_Click(object sender, EventArgs e)
        {
            var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
            DropDownList_CostCenter.Items.Clear();
            ListItem InsertItem = new ListItem("请选择", "");
            DropDownList_CostCenter.Items.Add(InsertItem);
            FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID));

            HiddenField_CurrentCenterId.Value = "";
        }

        private void DataBind(string SelectCenterId)
        {
            int MyCenterId = Convert.ToInt32(SelectCenterId);
            var MyDataQuery = (from a in db.TABC_JS_CostCenterPathFramework
                              join c in db.TABC_DM_CostDivers on a.成本动因ID equals c.成本动因ID
                              join d in db.TABC_JS_CostCenter on a.目标中心ID equals d.作业中心ID
                              join b in
                                  (from e in db.TABC_JS_CostCenterPathDriver where e.会计期间ID == Application["accountPeriod"].ToString() && e.作业中心ID == Convert.ToInt32(SelectCenterId) select e)
                              on a.目标中心ID equals b.目标中心ID  into mytemp 
                              where a.作业中心ID == Convert.ToInt32(SelectCenterId)
                              from temp in mytemp.DefaultIfEmpty() orderby a.目标中心ID
                              select new 
                              {
                                  a.ID,
                                  a.成本动因ID,
                                  c.成本动因名称,
                                  a.目标中心ID,
                                  目标中心名称 = d.作业中心名称,
                                  动因量 =( temp == null? 0 :temp.动因量)
                                  

                              }).Distinct() ;


            GridView_CostCenterDriver.DataSource = MyDataQuery;
            GridView_CostCenterDriver.DataBind();

        }


        //填充历史期间的动因量到当前列表中。
        protected void Button_FullHistoryDirver_Click(object sender, EventArgs e)
        {
            int MyCenterId = Convert.ToInt32(HiddenField_CurrentCenterId.Value);

                        string MyQueryAccountPeriod = DropDownList_Year.SelectedValue.ToString() + DropDownList_Month.SelectedValue.ToString(); 

            if (GridView_CostCenterDriver.Rows.Count != 0)
            {

                for (int i = 0; i < GridView_CostCenterDriver.Rows.Count; i++)
                {
                    GridViewRow myrows = GridView_CostCenterDriver.Rows[i];

                    var MyDriver = from a in db.TABC_JS_CostCenterPathDriver
                                   where a.作业中心ID == MyCenterId
                                   && a.目标中心ID == Convert.ToInt32(myrows.Cells[0].Text)
                                   && a.会计期间ID == MyQueryAccountPeriod
                                   select a;
                    if (MyDriver.Count() == 1)
                    {
                        ((TextBox)myrows.Cells[4].FindControl("TextBox_DriverAmount")).Text = string.Format("{0:F2}",MyDriver.Single().动因量);
                    
                    }
                
                
                
                }
            
            
            
            
            }
        }


        //保存对动因量的修改
        protected void Button_Save_Click(object sender, EventArgs e)
        {
            int MyCenterId = Convert.ToInt32(HiddenField_CurrentCenterId.Value);

            var IsLock = (from a in db.TABC_JS_CostCenterPathDriver
                          where a.作业中心ID == MyCenterId
                          && a.会计期间ID == Application["accountPeriod"].ToString()
                          && a.锁定 == true
                          select a).Count();
            if (IsLock > 0)
            {

                alert = "<script>alert('当前作业中心被锁定');</script>";

                return;
            }


            if (!Page.IsValid)
            {
                alert = "<script>alert('非法数据输入,请修改');</script>";

                return;
            }

         



            try
            {
              

                //先要删除在路径设置上不存在的记录
                var MyDelQuery = from a in db.TABC_JS_CostCenterPathDriver
                                 where !(
                                 from b in db.TABC_JS_CostCenterPathFramework
                                  where b.作业中心ID ==  MyCenterId 
                                  select b.目标中心ID.ToString()
                                     ).Contains(a.目标中心ID.ToString())
                                 && a.作业中心ID == MyCenterId 
                                 && a.会计期间ID == Application["accountPeriod"].ToString()
                                 select a;
                db.TABC_JS_CostCenterPathDriver.DeleteAllOnSubmit(MyDelQuery);
                db.SubmitChanges();


                for (int i = 0; i < GridView_CostCenterDriver.Rows.Count; i++)
                {
                    GridViewRow myrows = GridView_CostCenterDriver.Rows[i];
                    var isExistRow = from a in db.TABC_JS_CostCenterPathDriver
                                     where a.作业中心ID == MyCenterId 
                                     && a.会计期间ID == Application["accountPeriod"].ToString()
                                     && a.目标中心ID == Convert.ToInt32(myrows.Cells[0].Text)
                                     select a;
                    if (isExistRow.Count() == 0)
                    {
                        TABC_JS_CostCenterPathDriver myNewRow = new TABC_JS_CostCenterPathDriver();
                        myNewRow.公司ID = "Hisun";
                        myNewRow.账套ID = "001";
                        myNewRow.会计期间ID = Application["accountPeriod"].ToString();
                        myNewRow.作业中心ID = MyCenterId;
                        myNewRow.目标中心ID = Convert.ToInt32(myrows.Cells[0].Text);
                        myNewRow.动因ID = Convert.ToInt32(myrows.Cells[2].Text);
                        string mynum = ((TextBox)myrows.Cells[4].FindControl("TextBox_DriverAmount")).Text;
                        myNewRow.动因量 = Convert.ToDecimal(mynum);
                        myNewRow.录入人 = Session[ServerVars.sysSessionUserName].ToString();

                        db.TABC_JS_CostCenterPathDriver.InsertOnSubmit(myNewRow);

                    }
                    else if (isExistRow.Count() == 1)
                    {
                        var myEditRow = isExistRow.Single();
                        string mynum = ((TextBox)myrows.Cells[4].FindControl("TextBox_DriverAmount")).Text;
                        myEditRow.动因量 = Convert.ToDecimal(mynum);
                        myEditRow.录入人 = Session[ServerVars.sysSessionUserName].ToString();               
                      }


                }
                                                                   
                db.SubmitChanges();
                alert = "<script>alert('更新数据成功');</script>";

            }
            catch
            {
                alert = "<script>alert('更新数据失败');</script>";
            }
        }

        protected void DropDownList_CostCenter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Panel_GridList.Visible == true)
            {
                Panel_GridList.Visible = false;
            
            }

            //绑定数据
            if (DropDownList_CostCenter.SelectedValue == "")
            {
                Response.Write("<script>alert('当前选择的作业中心不存在');</script>");
                HiddenField_CurrentCenterId.Value = "";
                return;
            }
            HiddenField_CurrentCenterId.Value = DropDownList_CostCenter.SelectedValue.ToString();

            DataBind(HiddenField_CurrentCenterId.Value);

            if (GridView_CostCenterDriver.Rows.Count == 0)
            {
                Panel_GridList.Visible = false;
            }
            else
            {
                AbcFullAccountPeriod MyFullAp = new AbcFullAccountPeriod();

                MyFullAp.FullAccountPeriodToDropdownlist(DropDownList_Year, DropDownList_Month, Application["accountPeriod"].ToString());
              
                Panel_GridList.Visible = true;
            }
        }

        //定义全局变量，并对列数据绑定事件进行编程。以显示汇总数据
        decimal totalcash = 0;
        protected void GridView_CostCenterDriver_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                totalcash += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "动因量"));
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "合计";
                e.Row.Cells[4].Text = totalcash.ToString("0.00");
            }
        }

        //显示目标作业中心列表
        protected void Button_Set_Click(object sender, EventArgs e)
        {
            //得到当前作业中心ID
            int MyCenterId = Convert.ToInt32(HiddenField_CurrentCenterId.Value);

            var CopyCenterlist = from h in
                                     (from a in db.TABC_JS_CostCenterPathFramework
                                      join b in db.TABC_JS_CostCenter
                                      on a.作业中心ID equals b.作业中心ID
                                      join d in db.TABC_DM_CostDivers
                                      on a.成本动因ID equals d.成本动因ID

                                      where a.成本动因ID == (from c in db.TABC_JS_CostCenterPathFramework
                                                         where c.作业中心ID == MyCenterId
                                                         select c.成本动因ID).Distinct().Single().Value
                                     && a.作业中心ID != MyCenterId
                                     && b.作业中心名称.Contains(TextBox_CopyFilter.Text)


                                      select new
                                      {
                                          a.作业中心ID,
                                          b.作业中心名称,
                                          a.成本动因ID,
                                          d.成本动因名称

                                      })
                                 group h by h.作业中心ID into g
                                 select new 
                                 {

                                     作业中心ID = g.Key,
                                     成本动因ID = g.Max(p => p.成本动因ID),
                                     作业中心名称= g.Max(p=>p.作业中心名称),
                                    // 成本动因ID= g.Max(p=>p.作业中心ID);
                                     成本动因名称= g.Max(p=>p.成本动因名称)
                                 }

                                     ;

            if (CopyCenterlist.Count() == 0)
            {
                Panel_CopyList.Visible = false;
            
            }
            else
            {
                Panel_CopyList.Visible = true;
                GridView_CoypList.DataSource = CopyCenterlist;
                GridView_CoypList.DataBind();
               
            
            }

        }

        //执行动因量的复制
        protected void Button_Execute_Click(object sender, EventArgs e)
        {
            string Ap = Application["accountPeriod"].ToString();

            try
            {
                //对目标作业路径上的作业中心进行第一层遍历
                for (int i = 0; i < GridView_CoypList.Rows.Count; i++)
                {
                    GridViewRow MyCopyCenterRow = GridView_CoypList.Rows[i];

                    if (((CheckBox)MyCopyCenterRow.Cells[4].FindControl("CheckBox_Select")).Checked == true)
                    {
                        //取当前目标路径的作业中心ID
                        int CopyCenterID = Convert.ToInt32(MyCopyCenterRow.Cells[0].Text);

                        for (int j = 0; j < GridView_CostCenterDriver.Rows.Count; j++)
                        {
                            //对动因录入作业中心列表进行第二层遍历。目标作业中心
                            GridViewRow MyGoalCenterRow = GridView_CostCenterDriver.Rows[j];
                            //取目标作业中心
                            int GoalCenterID = Convert.ToInt32(MyGoalCenterRow.Cells[0].Text);

                            var IsExist1 = from a in db.TABC_JS_CostCenterPathFramework
                                           where a.作业中心ID == CopyCenterID
                                           && a.目标中心ID == GoalCenterID
                                           select a;
                            if (IsExist1.Count() == 1)
                            {
                                var IsExist2 = from b in db.TABC_JS_CostCenterPathDriver
                                               where b.作业中心ID == CopyCenterID
                                               && b.目标中心ID == GoalCenterID
                                               && b.会计期间ID == Ap
                                               select b;
                                if (IsExist2.Count() == 0)
                                {
                                    TABC_JS_CostCenterPathDriver AddRow = new TABC_JS_CostCenterPathDriver();

                                    AddRow.公司ID = "Hisun";
                                    AddRow.账套ID = "001";
                                    AddRow.会计期间ID = Ap;
                                    AddRow.作业中心ID = CopyCenterID;
                                    AddRow.目标中心ID = GoalCenterID;
                                    AddRow.动因ID = Convert.ToInt32(MyGoalCenterRow.Cells[2].Text);
                                    string mynum = ((TextBox)MyGoalCenterRow.Cells[4].FindControl("TextBox_DriverAmount")).Text;
                                    AddRow.动因量 = Convert.ToDecimal(mynum);
                                    AddRow.录入人 = Session[ServerVars.sysSessionUserName].ToString();

                                    db.TABC_JS_CostCenterPathDriver.InsertOnSubmit(AddRow);

                                }
                                else if (IsExist2.Count() == 1)
                                {

                                    TABC_JS_CostCenterPathDriver EditRow = IsExist2.Single();
                                    string mynum = ((TextBox)MyGoalCenterRow.Cells[4].FindControl("TextBox_DriverAmount")).Text;
                                    EditRow.动因量 = Convert.ToDecimal(mynum);
                                    EditRow.录入人 = Session[ServerVars.sysSessionUserName].ToString();


                                }


                            }


                        }

                    }

                }


                db.SubmitChanges();
                alert = "<script>alert('复制动因量到目标作业路径成功');</script>";

                if (Panel_CopyDriver.Visible == true)
                {

                    Panel_CopyDriver.Visible = false;

                }
            }
            catch
            {
                alert = "<script>alert('复制动因量到目标作业路径失败');</script>";
            
            }    
            
              
        }

        protected void LinkButton_VisibleTheDriverCopyPanel_Click(object sender, EventArgs e)
        {

            if( Panel_GridList.Visible == false)
            {
                alert = "<script>alert('当前作业中心列表为空');</script>";

                return;
            
            }


            if( Panel_CopyDriver.Visible == false)
            {

                Panel_CopyDriver.Visible = true;


                TextBox_CopyFilter.Text = "";
            
            }
        }






        //protected void CheckBox_SelectAll_CheckedChanged(object sender, EventArgs e)
        //{
        //    bool MyCheck = false;

        //    if (((CheckBox)sender).Checked == true)
        //    {
        //        ((CheckBox)sender).Checked = false;
        //        MyCheck = false;
        //    }
        //    else
        //    {

        //        ((CheckBox)sender).Checked = true;
        //        MyCheck = true;
        //    }

        //    for (int i = 0; i < GridView_CoypList.Rows.Count; i++)
        //    {
        //        GridViewRow MyCopyCenterRow = GridView_CoypList.Rows[i];
        //        ((CheckBox)MyCopyCenterRow.Cells[4].FindControl("CheckBox_Selec")).Checked = MyCheck;
        //    }
        //}







    }
}
